﻿using G3WebERPApi.Model;
using Newtonsoft.Json;
using System;
using System.Collections;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;

namespace G3WebERPApi
{
    /// <summary>
    /// Sign 的摘要说明
    /// </summary>
    ///
    public class Sign : IHttpHandler
    {
        private string nonceStr = ToolsClass.GetConfig("RomensOA"); //必填，生成签名的随机串

        public void ProcessRequest(HttpContext context)
        {
            //判断客户端请求是否为post方法
            if (context.Request.HttpMethod.ToUpper() != "POST")
            {
                context.Response.Write(JsonConvert.SerializeObject(new CommonModel { errcode = "-1", errmsg = "请使用POST方式" }));
                return;
            }

            try
            {
                string CsJson;
                //获取请求json
                using (var reader = new StreamReader(context.Request.InputStream, Encoding.UTF8))
                {
                    CsJson = reader.ReadToEnd();
                }

                CsJson = Regex.Replace(CsJson, @"[\n\r]", "").Replace(@"\n", ",").Replace("'", "‘").Replace(@"\t", ":").Replace(@"\r", ",").Replace(@"\n", ",");
                //json转Hashtable
                object jgobj = ToolsClass.DeserializeObject(CsJson);
                if (!(jgobj is Hashtable returnhash))
                {
                    context.Response.Write(JsonConvert.SerializeObject(new CommonModel { errcode = "-1", errmsg = "报文格式错误" }));
                    return;
                }
                string signUrl = ToolsClass.GetConfig("signUrl"); context.Response.ContentType = "text/plain";
                string path = context.Request.Path.Replace("Sign.ashx", "getsign");
                //验证请求sign
                string sign = ToolsClass.md5(signUrl + path + "Romens1/DingDing2" + path, 32);
                ToolsClass.TxtLog("生成的sign", "生成的" + sign + "传入的sign" + returnhash["Sign"].ToString() + "\r\n 后台字符串:" + signUrl + path + "Romens1/DingDing2" + path);
                if (sign != returnhash["Sign"].ToString())
                {
                    context.Response.Write(JsonConvert.SerializeObject(new CommonModel { errcode = "-1", errmsg = "认证信息Sign不存在或者不正确" }));
                    return;
                }

                //#微应用ID:agentId #企业ID:corpId #应用的唯一标识:appKey #应用的密钥:appSecret
                string AppWyy = ToolsClass.GetConfig("AppWyy");
                string[] ScList = AppWyy.Split('$');
                string agentId = ScList[0].ToString();
                string corpId = ScList[1].ToString();
                string appKey = ScList[2].ToString();
                string appSecret = ScList[3].ToString();

                //获取access_token
                string url = "https://oapi.dingtalk.com/gettoken?appkey=" + appKey + "&appsecret=" + appSecret;
                string FhJson = ToolsClass.ApiFun("GET", url, "");

                CommonModel tokenClass = new CommonModel();
                tokenClass = (CommonModel)JsonConvert.DeserializeObject(FhJson, typeof(CommonModel));
                string access_token = tokenClass.access_token;
                if (tokenClass.errcode != "0")
                {
                    context.Response.Write(JsonConvert.SerializeObject(new CommonModel { errcode = "-1", errmsg = "获取ACCESS_TOKEN报错" }));
                    return;
                }

                //JSAPI鉴权
                url = returnhash["url"].ToString();
                FhJson = ToolsClass.ApiFun("GET", "https://oapi.dingtalk.com/get_jsapi_ticket?access_token=" + access_token, "");
                ToolsClass.TxtLog("DDLog", "Sign入参:" + CsJson + " appKey:" + appKey + " appsecret:" + appSecret + " access_token:" + access_token + " JSAPI鉴权Fh:" + FhJson);

                var signClass = (CommonModel)JsonConvert.DeserializeObject(FhJson, typeof(CommonModel));
                if (signClass.errcode != "0")
                {
                    context.Response.Write(JsonConvert.SerializeObject(new CommonModel { errcode = "-1", errmsg = "JSAPI鉴权报错" }));
                    return;
                }
                string timeStamp = GetTimeStamp();
                nonceStr = ToolsClass.GetRandomString(8);
                string assemble = string.Format("jsapi_ticket={0}&noncestr={1}&timestamp={2}&url={3}", signClass.ticket, nonceStr, timeStamp, url);
                SHA1 sha;
                ASCIIEncoding enc;
                sha = new SHA1CryptoServiceProvider();
                enc = new ASCIIEncoding();
                byte[] dataToHash = enc.GetBytes(assemble);
                byte[] dataHashed = sha.ComputeHash(dataToHash);
                sign = BitConverter.ToString(dataHashed).Replace("-", "");
                sign = sign.ToLower();

                string fh = JsonConvert.SerializeObject(new CommonModel
                { 
                    nonceStr = nonceStr,
                    timeStamp = timeStamp,
                    signature = sign,
                    agentId = agentId,
                    corpId = corpId,
                    errcode = "0",
                    errmsg = "ok",
                    url = url

                }); 
                ToolsClass.TxtLog("DDLog", "返回前端信息:" + fh + "\r\n");
                context.Response.Write(fh);
                return;
            }
            catch (Exception ex)
            {
                context.Response.Write(JsonConvert.SerializeObject(new CommonModel { errcode = "-1", errmsg = "服务器内部错误" }));
                ToolsClass.TxtLog("鉴权异常日志", ex.Message);
                return;
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        /// <summary>
        /// 获取时间戳timestamp（当前时间戳，具体值为当前时间到1970年1月1号的秒数）
        /// </summary>
        /// <returns></returns>
        public static string GetTimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds).ToString();
        }
    }
}